package h_10_25;

import java.util.HashMap;

/**
 * 3090. 每个字符最多出现两次的最长子字符串
 * https://leetcode.cn/problems/maximum-length-substring-with-two-occurrences/description/
 */
public class Main2 {
    public int maximumLengthSubstring(String s) {
        char[] ch = s.toCharArray();
        int n = ch.length;
        HashMap<Character,Integer> map = new HashMap<>();
        int left = 0;
        int right = 0;
        int ret = 0;
        while(right < n) {
            // 入
            char in = ch[right];
            map.put(in,map.getOrDefault(in,0) + 1);

            // 判断，这里需要从左侧进行出窗口，而每一次出的不一定就是超出的那个字符
            while(map.get(in) > 2) {
                // 出
                char out = ch[left];
                map.put(out,map.get(out) - 1);
                left++;
            }
            // 更新
            ret = Math.max(ret,right - left + 1);
            right++;
        }
        return ret;
    }
}
